package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.PageResult;
import com.heima.mapper.NodeMapper;
import com.heima.mapper.PartnerMapper;
import com.heima.mapper.VMMapper;
import com.heima.pojo.Node;
import com.heima.pojo.VendingMachine;
import com.heima.pojo.dto.VMAddDto;
import com.heima.pojo.dto.VMDto;
import com.heima.pojo.vo.NodeInfoVo;
import com.heima.pojo.vo.NodeVo;
import com.heima.service.VMService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class VMServiceImpl extends ServiceImpl<VMMapper, VendingMachine> implements VMService {

    private final VMMapper vmMapper;
    private final NodeMapper nodeMapper;;
    private final PartnerMapper partnerMapper;

    private final static Integer VM_STATUS = 1;

    @Override
    public PageResult<NodeInfoVo> searchVMInfo(VMDto vmDto) {
        PageHelper.startPage(vmDto.getPageIndex(), vmDto.getPageSize());
        Page<NodeInfoVo> list = vmMapper.findByInnerCode(vmDto);

        // 计算总页数
        //int totalPage = (int) Math.ceil((double) list.getTotal() / vmDto.getPageSize());
        return new PageResult<>(
                vmDto.getPageIndex(),
                vmDto.getPageSize(),
                list.getPageSize(),
                list.getTotal(),
                list.getResult()
        );
    }

    @Override
    public Boolean saveVM(VMAddDto vmAddDto) {
        VendingMachine machine = new VendingMachine();

        // 先拷贝基础字段
        BeanUtils.copyProperties(vmAddDto, machine);

        // nodeId 类型转换（如果 DTO 是 String 类型）
        if (vmAddDto.getNodeId() != null) {
            machine.setNodeId(Long.valueOf(vmAddDto.getNodeId()));
        }

        // 根据 nodeId 查询 Node 信息
        Node node = nodeMapper.getNodeById(machine.getNodeId());
        if (node != null) {
            machine.setNodeId(node.getId());
            machine.setBusinessId(node.getBusinessId());
            machine.setRegionId(Long.valueOf(node.getRegionId())); // 修正之前错误赋值
            machine.setOwnerId(node.getOwnerId());
            machine.setOwnerName(node.getOwnerName());
            machine.setCreateUserId(Long.valueOf(node.getCreateUserId()));
            String createUserName = nodeMapper.getCreateUserName(node.getCreateUserId());
            machine.setCreateUserName(createUserName);
            machine.setCityCode(node.getAreaCode()); // node 的 cityCode 覆盖
        }

        // 如果 cityCode 为空（防止 node 没查到），从 partnerMapper 获取
        if (machine.getCityCode() == null && machine.getOwnerId() != null) {
            String cityCode = partnerMapper.cityCode(machine.getOwnerId());
            machine.setCityCode(cityCode);
        }

        String maxInnerCode = vmMapper.findMaxInnerCode(machine.getCityCode());
        int nextSeq = 1;
        if (maxInnerCode != null) {
            Pattern pattern = Pattern.compile("(\\d{5})$");
            Matcher matcher = pattern.matcher(maxInnerCode);
            if (matcher.find()) {
                nextSeq = Integer.parseInt(matcher.group(1)) + 1;
            }
        }
        String innerCode = machine.getCityCode() + String.format("%05d", nextSeq);
        machine.setInnerCode(innerCode);

        //partnerMapper.areaId()

        // 通用字段赋值
        machine.setVmStatus(VM_STATUS);
        machine.setCreateTime(new Date());
        machine.setUpdateTime(new Date());
        machine.setClientId(UUID.randomUUID().toString());

        return super.save(machine);
    }

    @Override
    public Boolean updateVM(Integer id, String nodeId) {
        return vmMapper.updateNode(id, nodeId) > 0;
    }

}
